<?php
/*
 * @Author: lokei
 * @Date: 2022-08-08 22:55:21
 * @LastEditors: lokei
 * @LastEditTime: 2023-03-06 22:46:20
 * @Description: 
 */

namespace App\Http\Controllers\Rbac\Auth;

use App\Common\Qyapi\Common;
use App\Common\Tools\ResultTool;
use App\Http\Controllers\Controller;
use App\Models\Ucenter\FansModel;
use App\Models\Ucenter\UserModel;
use App\Services\Ucenter\FansService;
use App\Services\Ucenter\UserService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class QwController extends Controller
{

    private UserService $user_service;

    private FansService $fans_service;

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
        $this->user_service = new UserService();
        $this->fans_service = new FansService();
    }

    //

    public function code(Request $request)
    {
        $params = [];
        $suite_access_token = Common::getSuiteAccessToken(config('app.open_mode'));
        $params_str = json_encode($params, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE);
        
        $ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, 'https://qyapi.weixin.qq.com/cgi-bin/service/auth/getuserinfo3rd?suite_access_token=' . $suite_access_token . '&code=' . $request->input('code'));
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $params_str); // 必须为字符串
		curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); // 必须声明请求头
		// 如果没有错误的话返回的就是小程序码的文件流
		$result_str = curl_exec($ch);
		$result = json_decode($result_str, true);

        if (array_key_exists('errcode', $result) && $result['errcode'] != 0) {
            $res = ResultTool::fail();
            $res['errorCode'] = $result['errcode'];
            $res['errorMsg'] = $result['errmsg'];
            return $res;
        }
        if ((array_key_exists('openid', $result) && $result['openid'] != '') || (array_key_exists('open_userid', $result) && $result['open_userid'] != '')) {
            $openid = array_key_exists('openid', $result) ? $result['openid'] : $result['open_userid'];
            $fans = FansModel::where('openid', '=', $openid)->where('platform', '=', 'qy')->first();
            if (!is_null($fans)) {
                if (!($fans->uid > 0)) {
                    $uid = $this->user_service->createUser();
                    $fans->uid = $uid;
                    $fans->save();
                }
            } else {
                $this->fans_service->registerOpenid('qy', $openid);
                $fans = FansModel::where('openid', '=', $openid)->first();
                if(array_key_exists('userid', $result)) {
                    $fans->qy_userid = $result['userid'];
                }
                if(array_key_exists('corpid', $result)) {
                    $fans->corpid = $result['corpid'];
                }
                $uid = $this->user_service->createUser();
                $fans->uid = $uid;
                $fans->save();
            }
            $user = UserModel::where('uid', '=', $fans->uid)->first();
            $token = Auth::login($user);
            $res = ResultTool::success();
            $res['data']['token'] = $token;
            if(array_key_exists('corpid', $result)) {
                $res['data']['corpid'] = $result['corpid'];
            }
            return $res;
        }
        $res = ResultTool::fail();
        $res['errorMsg'] = '企业微信公众号用户登入失败！';
        return $res;
    }
}
